
import 'package:cached_network_image/cached_network_image.dart';
import 'package:chatgreat/helper/AppUtil.dart';
import 'package:chatgreat/helper/color.dart';
import 'package:chatgreat/helper/my_widget.dart';
import 'package:chatgreat/page/chat/home.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/dialog.dart';
import 'package:chatgreat/page/component/sliver_component.dart';
import 'package:chatgreat/page/component/theme/custom_size.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/get_state_manager.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
// import 'package:stripe_js/stripe_js.dart';

import '../../../helper/event.dart';
import '../../../helper/helper.dart';
import '../../../repo/api_server.dart';
import '../../../repo/model/gallery_home_model.dart';
import '../../../widgets/flutter_life_state/src/base_life_state.dart';
import '../../component/button.dart';
import '../../component/enhanced_textfield.dart';
import '../../component/loading.dart';
import 'data/gallery_home_data.dart';

class GalleryCreateScreen extends StatefulWidget {
  final SettingRepository setting;

  const GalleryCreateScreen({
    super.key,
    required this.setting,
  });

  @override
  State<GalleryCreateScreen> createState() => _GalleryCreateScreenState();
}

enum GenerateStatus { display, generating, over }

class _GalleryCreateScreenState extends BaseLifeState<GalleryCreateScreen> {
  final TextEditingController _titleTextController = TextEditingController();
  final TextEditingController _contentTextController = TextEditingController();

  final ScrollController _titleScrollController = ScrollController();
  final ScrollController _contentScrollController = ScrollController();
  final ScrollController _sizeScrollController = ScrollController();

  int _currentIndex = 0; // 当前选择风格标题下标
  int _currentStyleIndex = 0; // 当前选择风格内容下标 -1
  int _currentSizeIndex = 0; // 当前选择大小下标
  bool enableNotifier = true;

  var isEnabelButton = true.obs; //改成默认选中，则一直可点击
  final GalleryHomeData _homeData = GalleryHomeData();

  var firstLoad = true;

  @override
  void initState() {
    super.initState();

    Future.delayed(const Duration(milliseconds: 400)).then((value) {
      _homeData.loadData().then((value) => setState(() {
        if (_currentStyleIndex >= 0) {
          var currentStyles = _homeData.styleList[_currentIndex];
          if ((currentStyles.styles?.length ?? 0) > 0) {
            var style = currentStyles.styles?[_currentStyleIndex];
            _titleTextController.text = style?.name ?? "";
            _contentTextController.text = style?.remark ?? "";
          }
        }
      }));
    });
    _titleTextController.addListener(() {
      adjEnableButton();
    });
    _contentTextController.addListener(() {
      adjEnableButton();
    });
    GlobalEvent().on("refresh_2", (data) {
      if (mounted) {
        _homeData.loadData().then((value) => setState(() { }));
        AppUtil().updateUserInfo();
      }
    });
  }

  @override
  void onResumed() {
    //其他页面路由返回才触发
    super.onResumed();
    if (firstLoad) {
      firstLoad = false;
      return;
    }
    print('--------------> 开始绘画 onResumed ');
    _homeData.loadData().then((value) => setState(() { }));
    AppUtil().updateUserInfo();
  }

  @override
  void dispose() {
    _titleTextController.dispose();
    _contentTextController.dispose();
    _titleScrollController.dispose();
    _contentScrollController.dispose();
    _sizeScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BackgroundContainer(
      enabled: false,
      setting: widget.setting,
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SliverCreateComponent(
          child: Column(
            children: [
              Expanded(
                  child: CustomScrollView(
                shrinkWrap: true,
                slivers: [
                  SliverToBoxAdapter(child: _buildTopWidget()),
                  SliverToBoxAdapter(child: _buildBottomTitleWidget()),
                  SliverToBoxAdapter(child: _buildBottomContentWidget()),
                  SliverToBoxAdapter(child: _buildSizeWidget()),
                ],
              )),
              Obx(
                () => Container(
                  height: 50,
                  margin:
                      const EdgeInsets.only(left: 19, right: 19, bottom: 20),
                  width: double.infinity,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(isEnabelButton.value
                          ? 'images/guide_button.png'
                          : 'images/guide_button_unselected.png'),
                      fit: BoxFit.fill,
                    ),
                  ),
                  child: CupertinoButton(
                    padding: EdgeInsets.zero,
                    child:
                        MyTextWeight('开始画画', 16, Colors.white, FontWeight.w500),
                    onPressed: () async {
                      if (!isEnabelButton.value) return;
                      FocusScope.of(context).requestFocus(FocusNode());

                      if (AppUtil().touristLoginModel?.isVip == 0) {
                        // 不是vip需要跳转
                        // context.push('/payment');
                        showVipGlobalDialog(context);
                        return;
                      }
                      if (_homeData.needIntegral.value > _homeData.integral.value) {
                        // 积分不足
                        // showErrorMessage('积分不足');
                        context.push('/integral');
                        return;
                      }

                      // 积分满足
                      showIntegralTipsDialog(context, () {
                        var currentSize = _homeData.sizeList[_currentSizeIndex];
                        var extra = {};
                        extra['sizeId'] = currentSize.id;
                        if (_currentStyleIndex >= 0) {
                          // 选了风格
                          var currentStyles = _homeData.styleList[_currentIndex];
                          if ((currentStyles.styles?.length ?? 0) > 0) {
                            var style = currentStyles.styles?[_currentStyleIndex];
                            extra['styleId'] = style?.id;
                            if (_titleTextController.text.isNotEmpty) {
                              extra['title'] = _titleTextController.text;
                            } else {
                              extra['title'] = style?.name;
                            }
                            if (_contentTextController.text.isNotEmpty) {
                              extra['content'] = _contentTextController.text;
                            } else {
                              extra['content'] = style?.remark;
                            }
                          }
                        } else {
                          // 没选风格
                          if (_titleTextController.text.isNotEmpty) {
                            extra['title'] = _titleTextController.text;
                          }
                          if (_contentTextController.text.isNotEmpty) {
                            extra['content'] = _contentTextController.text;
                          }
                        }

                        Future.delayed(const Duration(milliseconds: 400)).then((value) {
                          context.push('/gallery_start_create', extra: extra);
                        });
                      });
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTopWidget() {
    final customColors = Theme.of(context).extension<CustomColors>()!;
    return Padding(
      padding: const EdgeInsets.only(left: 16, right: 16, top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 2),
            child: MyTextWeight(
                '输入要画的对象', 14, Colors.white.withOpacity(0.6), FontWeight.w400),
          ),
          Container(
            margin: const EdgeInsets.only(top: 8, bottom: 20),
            padding: const EdgeInsets.only(left: 15, right: 10),
            height: 64,
            decoration: BoxDecoration(
              color: stringToColor('FF21222F'),
              borderRadius: BorderRadius.circular(6.0),
            ),
            child: EnhancedTextField(
              onFocusChange: (hasFocus) {},
              controller: _titleTextController,
              enabled: enableNotifier,
              customColors: customColors,
              maxLines: 1,
              hintText: '例如：飞机、机器人、小男孩...',
              maxLength: 10,
              showCounter: true,
              keyboardType: TextInputType.text,
              hintColor: const Color(0xFF999999),
              hintTextSize: 15,
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 2),
            child: MyTextWeight('下方自主输入画画风格的具体要求，或选择下方设定风格', 14,
                Colors.white.withOpacity(0.6), FontWeight.w400),
          ),
          Container(
            margin: const EdgeInsets.only(top: 8, bottom: 25),
            padding: const EdgeInsets.only(left: 15, right: 10),
            height: 140,
            decoration: BoxDecoration(
              color: stringToColor('FF21222F'),
              borderRadius: BorderRadius.circular(6.0),
            ),
            child: EnhancedTextField(
              onFocusChange: (hasFocus) {},
              controller: _contentTextController,
              enabled: enableNotifier,
              customColors: customColors,
              maxLines: 4,
              hintText: '例如：高光，人像摄影，清晰五官，纯色背景，亚洲脸型',
              maxLength: 200,
              showCounter: true,
              keyboardType: TextInputType.text,
              hintColor: const Color(0xFF999999),
              hintTextSize: 15,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomTitleWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 18),
          child: MyTextWeight(
              '选择风格', 14, Colors.white.withOpacity(0.6), FontWeight.w400),
        ),
        Container(
          width: double.infinity,
          height: 31,
          margin: const EdgeInsets.only(top: 17.5),
          child: GridView.count(
            physics: const AlwaysScrollableScrollPhysics(),
            crossAxisCount: 1,
            childAspectRatio: 31 / 75,
            scrollDirection: Axis.horizontal,
            mainAxisSpacing: 10,
            padding: const EdgeInsets.only(left: 16, right: 16),
            controller: _titleScrollController,
            children: _getTitleWidgets(),
          ),
        )
      ],
    );
  }

  /// 获取title widget视图
  List<Widget> _getTitleWidgets() {
    List<Widget> widgets = [];
    for (int i = 0; i < _homeData.styleList.length; i++) {
      StyleList model = _homeData.styleList[i];
      widgets.add(_titleItemWidget(model, i));
    }
    if (widgets.isEmpty) {
      widgets.add(Center(
        child: LoadingAnimationWidget.horizontalRotatingDots(
          color: stringToColor('FF18DDEB'),
          size: 31,
        ),
      ));
    }
    return widgets;
  }

  /// item视图
  Widget _titleItemWidget(StyleList model, int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _currentIndex = index;
          _currentStyleIndex = -1;
          adjEnableButton();
        });
      },
      child: Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16.0),
              border: Border.all(
                  width: 1,
                  color: _currentIndex == index
                      ? stringToColor('FF18DDEB')
                      : Colors.white.withOpacity(0.5))),
          child: MyTextWeight(
              model.name ?? '',
              15,
              _currentIndex == index
                  ? stringToColor('FF18DDEB')
                  : Colors.white.withOpacity(0.5),
              FontWeight.w500)),
    );
  }

  Widget _buildBottomContentWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: double.infinity,
          height: 100,
          margin: const EdgeInsets.only(top: 15),
          child: GridView.count(
            physics: const AlwaysScrollableScrollPhysics(),
            crossAxisCount: 1,
            childAspectRatio: 100 / 70,
            scrollDirection: Axis.horizontal,
            mainAxisSpacing: 10,
            padding: const EdgeInsets.only(left: 16, right: 16),
            controller: _contentScrollController,
            children: _getContentWidgets(),
          ),
        )
      ],
    );
  }

  /// 获取内容 widget视图
  List<Widget> _getContentWidgets() {
    List<Widget> widgets = [];

    if (_homeData.styleList.isNotEmpty) {
      var model = _homeData.styleList[_currentIndex];
      var styles = model.styles ?? [];
      for (int i = 0; i < styles.length; i++) {
        Style style = styles[i];
        widgets.add(_contentItemWidget(style, i));
      }
    }
    if (widgets.isEmpty) {
      widgets.add(Center(
        child: LoadingAnimationWidget.horizontalRotatingDots(
          color: stringToColor('FF18DDEB'),
          size: 31,
        ),
      ));
    }
    return widgets;
  }

  /// item视图
  Widget _contentItemWidget(Style model, int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _currentStyleIndex = index;
          adjEnableButton();

          // 测试需要去掉回填
          if (_currentStyleIndex >= 0) {
            var currentStyles = _homeData.styleList[_currentIndex];
            if ((currentStyles.styles?.length ?? 0) > 0) {
              var style = currentStyles.styles?[_currentStyleIndex];
              _titleTextController.text = style?.name ?? "";
              _contentTextController.text = style?.remark ?? "";
            }
          }
        });
      },
      child: Container(
          alignment: Alignment.center,
          child: Column(
            children: [
              Container(
                width: 70,
                height: 70,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10.0),
                    border: Border.all(
                        width: 2,
                        color: _currentStyleIndex == index
                            ? stringToColor('FF18DDEB')
                            : Colors.transparent)),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8.0),
                  child: CachedNetworkImage(
                    imageUrl: model.cover ?? '',
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              const SizedBox(height: 7),
              Expanded(
                child: MyTextWeight(model.name ?? '', 13,
                    Colors.white.withOpacity(0.6), FontWeight.w500),
              ),
            ],
          )),
    );
  }

  /// size widget
  Widget _buildSizeWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 18, top: 20),
          child: MyTextWeight(
              '选择尺寸', 14, Colors.white.withOpacity(0.6), FontWeight.w400),
        ),
        Container(
          width: double.infinity,
          height: 31,
          margin: const EdgeInsets.only(top: 17.5, bottom: 16),
          child: GridView.count(
            crossAxisCount: 1,
            childAspectRatio: 31 / 75,
            scrollDirection: Axis.horizontal,
            mainAxisSpacing: 10,
            padding: const EdgeInsets.only(left: 16, right: 16),
            controller: _sizeScrollController,
            children: _getSizeWidgets(),
          ),
        )
      ],
    );
  }

  /// 获取size widget视图
  List<Widget> _getSizeWidgets() {
    List<Widget> widgets = [];
    for (int i = 0; i < _homeData.sizeList.length; i++) {
      SizeList model = _homeData.sizeList[i];
      widgets.add(_sizeItemWidget(model, i));
    }
    if (widgets.isEmpty) {
      widgets.add(Center(
        child: LoadingAnimationWidget.horizontalRotatingDots(
          color: stringToColor('FF18DDEB'),
          size: 31,
        ),
      ));
    }
    return widgets;
  }

  /// item视图
  Widget _sizeItemWidget(SizeList model, int index) {
    var sizes = model.title?.split(':');
    var width = double.parse(sizes?.first ?? '1');
    if (width == 1) {
      width = 11.0;
    } else if (width == 3) {
      width = 10.0;
    } else if (width == 4) {
      width = 12.0;
    }
    var height = double.parse(sizes?.last ?? '1');
    if (height == 1) {
      height = 11.0;
    } else if (height == 3) {
      width = 10.0;
    } else if (height == 4) {
      width = 12.0;
    }
    return GestureDetector(
      onTap: () {
        setState(() {
          _currentSizeIndex = index;
        });
      },
      child: Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16.0),
              border: Border.all(
                  width: 1,
                  color: _currentSizeIndex == index
                      ? stringToColor('FF18DDEB')
                      : Colors.white.withOpacity(0.5))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CustomPaint(
                size: Size(width, height),
                painter: RectanglePainter(_currentSizeIndex == index
                    ? stringToColor('FF18DDEB')
                    : Colors.white.withOpacity(0.5)),
              ),
              const SizedBox(width: 5),
              MyTextWeight(
                  model.title ?? '',
                  15,
                  _currentSizeIndex == index
                      ? stringToColor('FF18DDEB')
                      : Colors.white.withOpacity(0.5),
                  FontWeight.w500),
            ],
          )),
    );
  }

  adjEnableButton() {
    if (_currentStyleIndex == -1) {
      if (_titleTextController.text.isEmpty ||
          _contentTextController.text.isEmpty) {
        isEnabelButton.value = false;
        return;
      }
    }
    isEnabelButton.value = true;
  }

  /// 显示积分提醒
  showIntegralTipsDialog(BuildContext context, Function()? onSubmitCallback) async {

    showAnimationDialog(
      context: context,
      transitionType: TransitionType.inFromTop,
      barrierDismissible: true,
      builder: (diaContext) => StatefulBuilder(builder: (diaContext, state) {
        return Dialog(
          elevation: 0,
          backgroundColor: Colors.transparent,
          child: Container(
            margin: const EdgeInsets.only(bottom: 30),
            width: 320,
            height: 275,
            decoration: BoxDecoration(
              color: const Color(0xFF333544),
              borderRadius: BorderRadius.circular(13),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 34),
                  child: MyTextWeight('绘画消耗积分', 18, Colors.white, FontWeight.w500),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 30, bottom: 25),
                  child: MyTextWeight('每次绘画消耗${_homeData.needIntegral.value}积分，是否确定画画', 16, Colors.white, FontWeight.w400),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    MyTextWeight('当前积分：', 16, Colors.white, FontWeight.w400),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 5),
                      child: MyTextWeight('${_homeData.integral.value}', 24, const Color(0xFF18DDEB), FontWeight.w500),
                    ),
                  ],
                ),
                const Spacer(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Button(
                        title: '取消',
                        color: const Color(0xFF666666),
                        size: const ButtonSize(
                            height: 40, width: 125, fontSize: 16),
                        backgroundColor: const Color(0xFFEEEEEE),
                        borderRadius: 20,
                        onPressed: () {
                          diaContext.pop();
                        }),
                    const SizedBox(width: 12),
                    Button(
                        title: '确定',
                        color: Colors.white,
                        size: const ButtonSize(
                            height: 40, width: 125, fontSize: 16),
                        backgroundColor: const Color(0xFFEEEEEE),
                        borderRadius: 20,
                        gradient: const LinearGradient(
                          colors: [
                            Color(0xFF14E0EB),
                            Color(0xFF5988FC),
                          ],
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                        ),
                        onPressed: () {
                          if (onSubmitCallback != null) {
                            onSubmitCallback();
                          }
                          diaContext.pop();
                        }),
                  ],
                ),
                const SizedBox(height: 25),
              ],
            ),
          ),
        );
      }),
    );
  }
}

class RectanglePainter extends CustomPainter {
  final Color paintColor;

  RectanglePainter(this.paintColor);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = paintColor // 定义矩形的颜色
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke; // 定义绘制样式

    canvas.drawRRect(
      RRect.fromRectAndCorners(Rect.fromLTWH(0, 0, size.width, size.height),
          topRight: const Radius.circular(2),
          topLeft: const Radius.circular(2),
          bottomLeft: const Radius.circular(2),
          bottomRight: const Radius.circular(2)), // 定义矩形的位置和大小
      paint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true; // 是否需要重绘，这里返回false表示只绘制一次
  }
}
